/*
 * @Author: szx
 * @Date: 2021-11-10 18:28:08
 * @LastEditTime: 2021-11-10 18:47:20
 * @Description:
 * @FilePath: \leetcode\1-99\15\15.cpp
 */
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
   public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        vector<vector<int>> v;
        int n = nums.size();
        if (n < 3 || nums.back() < 0 || nums.front() > 0) return {};

        // k为target的负数
        for (int k = 0; k < n - 2; k++) {
            if (nums[k] > 0) break;
            if (k > 0 && nums[k] == nums[k - 1]) continue;
            int i = k + 1, j = n - 1;
            int target = -nums[k];
            while (i < j) {
                if (nums[j] < 0) break;

                if (nums[i] + nums[j] == target) {
                    v.push_back({nums[k], nums[i], nums[j]});
                    while (i < j && nums[i] == nums[i + 1]) ++i;
                    while (i < j && nums[j] == nums[j - 1]) --j;
                    ++i;
                    --j;
                } else if (nums[i] + nums[j] < target)
                    ++i;
                else
                    --j;
            }
        }
        return v;
    }
};
int main() { return 0; }